package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.Utils.ValidateCodeUtils;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request){
        //1.获取手机号
        String phone = user.getPhone();
        //2.生成随机的4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //3.调用阿里云提供的短信服务API完成发送短信
        log.info("code={}",code);
        //将生成的code存放到session中
        request.getSession().setAttribute(phone,code);

        return R.success("验证码发送成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String> map,HttpServletRequest request){
        log.info(map.toString());
        //获取手机号码
        String phone = map.get("phone");
        //获取验证码
        String code1 = map.get("code");
        //从session中获取发送的验证码
        String code2 = (String)request.getSession().getAttribute(phone);
        //1.判断验证码是否相等
        if (!StringUtils.equals(code1,code2)){
            return R.error("验证码错误");
        }

        //2.判断当前用户是否为新用户, 如果是新用户则自动完成注册
        //2.1获取改用户对象
        //创建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        User user = userService.getOne(queryWrapper);

        //2.2 如果是新用户则直接注册
        if (user==null){
            User user1 = new User();
            user1.setPhone(phone);
            user1.setStatus(1);
            userService.save(user1);
        }
        //2.3 不是新用户,则将用户信息存到session中
        request.getSession().setAttribute("user",user.getId());

        return R.success(user);
    }

}

